package service

import (
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_config/handler"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_config/model"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_config/repository"
)

type RegisterData struct {
	Type    string
	IP      string
	AppTeam string
}

// 接收前端注册服务信号，注册服务
func PostServiceRegister(context *gin.Context) {

	var param RegisterData
	err := context.BindJSON(&param) // 前后端交互参数
	if err != nil {                 // 错误处理
		log.Printf("ERROR: Register service failed, error is %v", err)
		context.JSON(500, gin.H{"err": err})
		return
	}

	dc2dc := map[string]string{
		"北京数据中心":    "pek",
		"内蒙数据中心":    "nm",
		"上海数据中心":    "sh",
		"合肥数据中心":    "hf",
		"内蒙数据中心-和林": "nm-zj",
	}

	ipParts := strings.Split(param.IP, "\n")
	log.Println("INFO: The ip for register is ", ipParts)
	var cmdbDataArr []model.CmdbAllServer
	var dcArr []string
	for _, ipValue := range ipParts {
		if ipValue != "" {
			DB := repository.GetDB()
			var Data []model.CmdbAllServer
			DB.Table("cmdb_all_servers").Where("ip = ?", ipValue).Find(&Data) // 根据IP，从mysql库中获取数据
			cmdbDataArr = append(cmdbDataArr, Data[0])
			if !handler.Contains(dcArr, dc2dc[Data[0].Datacenter]) && Data[0].Datacenter != "" { // 如果变量中没出现过该数据中心，则将该数据中心添加到变量中
				dcArr = append(dcArr, dc2dc[Data[0].Datacenter])
			}
		}
	}
	dcIndex := make(map[string]int)
	if len(dcArr) > 1 {
		for _, dcValue := range dcArr {
			dcIndex[dcValue] = handler.CheckServerVolume(dcValue)
			if dcIndex[dcValue] == 0 {
				log.Printf("ERROR: The %v prometheus server check failed.", dcValue)
				panic("Prometheus server check failed")
			}
		}

	} else {
		dcIndex[dcArr[0]] = handler.CheckServerVolume(dcArr[0])
		if dcIndex[dcArr[0]] == 0 {
			log.Printf("ERROR: Prometheus server check failed")
			panic("Prometheus server check failed")
		}
	}

	var reOutCome string

	for index, cmdbData := range cmdbDataArr {

		serviceData := model.FuncServiceRegister{
			ExporterType: param.Type,
			Datacenter:   dc2dc[cmdbData.Datacenter],
			MinIndex:     strconv.Itoa(dcIndex[dc2dc[cmdbData.Datacenter]]),
			ShortName:    cmdbData.ShortName,
			Hostname:     cmdbData.Hostname,
			IP:           cmdbData.IP,
			AppTeam:      param.AppTeam,
			ServiceName:  cmdbData.SystemName,
			SystemID:     strconv.Itoa(cmdbData.ProjectID),
		}
		log.Printf("INFO: Register data is ", serviceData)
		state := handler.ServiceRegisterSingle(index, serviceData)

		var reOutComeSingle string
		if state {
			reOutComeSingle = cmdbData.IP + ": " + param.Type + " service register success"
		} else {
			reOutComeSingle = cmdbData.IP + ": " + param.Type + " service register failed"
		}
		reOutCome = reOutCome + reOutComeSingle + "\n"
		log.Printf("INFO: ", reOutComeSingle)
	}

	type jsonData struct {
		Code int
		Data string
	}
	data := jsonData{
		Code: 200,
		Data: reOutCome,
	}
	context.JSON(http.StatusOK, data)
}
